using System;
using System.Windows;
using System.Windows.Browser;

namespace MoonRainbow.Input.Mouse
{
    internal abstract class MouseBehavior
    {
        static MouseBehavior()
        {
            var curEl = HtmlPage.Plugin;
            var index = 0;
            while (true)
            {
                if (curEl.Parent == null) break;
                if (curEl.Parent.TagName == "body") break;
                curEl = curEl.Parent;
                if (!string.IsNullOrEmpty(curEl.Id)) continue;
                curEl.SetAttribute("id", "parent" + index);
                index++;
            }
        }

        public event EventHandler<MouseEventDetectedEventArgs> MouseEventDetected;

        protected void InvokeMouseEventDetected(MouseEventDetectedEventArgs e)
        {
            var detected = MouseEventDetected;
            if (detected != null) detected(this, e);
        }

        protected static Point GetPosition(HtmlElement element)
        {
            var left = Convert.ToDouble(
                HtmlPage.Window.Eval(@"result = document.getElementById('" + element.Id +
                                     "').offsetParent.offsetLeft;"));
            var top = Convert.ToDouble(
                HtmlPage.Window.Eval(@"result = document.getElementById('" + element.Id +
                                     "').offsetParent.offsetLeft;"));
            if (element.Parent == null||element.Parent.TagName == "body")
                return new Point(left, top);
            var point = GetPosition(element.Parent);
            left += point.X;
            top += point.Y;
            return new Point(left, top);
        }
    }
}